package apis.amapv2.com.shake;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private Context mContext;
    private SensorManager mSensorManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mContext = this;

        TextView tvShake = findViewById(R.id.tv_shake);
        tvShake.setOnClickListener(this);

        //获得管理传感器
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        //获得加速度传感器
        Sensor defaultSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        //管理器注册监听
        mSensorManager.registerListener(mListener, defaultSensor, SensorManager.SENSOR_DELAY_UI);
    }

    //传感加速器的监听
    SensorEventListener mListener  = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            Log.e(TAG,"onSensorChanged");
            int type = event.sensor.getType();

            if (type == Sensor.TYPE_ACCELEROMETER) {
                //获取三个方向值
                float[] values = event.values;
                float x = values[0];
                float y = values[1];
                float z = values[2];
                //判断是否满足摇一摇的条件
                if ((Math.abs(x) > 25 || Math.abs(y) > 25 || Math.abs(z) > 77)) {
                    Toast.makeText(mContext, "摇一摇！", Toast.LENGTH_SHORT).show();
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注意：1、解除这个监听必须要做
        //2、如果不做，那么即使跳到别的页面，那么依然会执行传感器的回调。
        //3、具体在哪个回调方法里面开启，在哪个回调方法里面关闭，针对具体的情况而定。
        //可以在onResume中注册传感器的监听，可以在onPause中解除传感器的监听
        mSensorManager.unregisterListener(mListener);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_shake) {
            startActivity(new Intent(mContext,TestActivity.class));
        }
    }
}
